package com.yygo.webapp.controller;

import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;
import com.yygo.model.Notice;
import com.yygo.webapp.controller.BaseFormController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Controller
@RequestMapping("/noticeform*")
public class NoticeFormController extends BaseFormController {
    private GenericManager<Notice, Long> noticeManager = null;

    @Autowired
    public void setNoticeManager(@Qualifier("noticeManager") GenericManager<Notice, Long> noticeManager) {
        this.noticeManager = noticeManager;
    }

    public NoticeFormController() {
        setCancelView("redirect:notices");
        setSuccessView("redirect:notices");
    }

    @ModelAttribute
    @RequestMapping(method = RequestMethod.GET)
    protected Notice showForm(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            return noticeManager.get(new Long(id));
        }

        return new Notice();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(Notice notice, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
    throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        if (validator != null) { // validator is null during testing
            validator.validate(notice, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "noticeform";
            }
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (notice.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            noticeManager.remove(notice.getId());
            saveMessage(request, getText("notice.deleted", locale));
        } else {
            noticeManager.save(notice);
            String key = (isNew) ? "notice.added" : "notice.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                success = "noticeform";
            }
        }

        return success;
    }
}
